<template>
	<view class="message">
		<uni-nav-bar dark :fixed="true" :border="false" background-color="#FFFFFF" status-bar 
			title="消息通知" left-icon="left" @clickLeft="toBack" color="#000" />
		<u-sticky offset-top="64">
			<u-subsection :list="list" :current="curNow" @change="sectionChange"></u-subsection>
		</u-sticky>
		<scroll-view class="message-body" :scroll-y="true" :refresher-enabled="true" 
			:refresher-triggered="triggered" @refresherrefresh="onRefresh" 
			@refresherrestore="onRestore" @scrolltolower="onScroll">
			<view class="message-row" v-for="(item,index) in msgList" :key="item.id">
				<view style="flex: 1;display: flex;" @click="toPage(item)">
					<view style="width: 80rpx;">
						<u-avatar :size="30" :src="READ_IMG_URL+item.publisherImg"></u-avatar>
					</view>
					<view style="flex: 1;">
						<view style="font-size: 35rpx;font-weight: 800;">
							<text>{{item.title}}</text>
						</view>
						<view style="width: 100%;padding: 10rpx 0;">
							<text>{{item.content}}</text>
						</view>
						<view style="font-size: 25rpx;color: #909399;">
							<text>{{item.publisherName}}</text>
							<text style="margin-left: 20rpx;">
								{{formatTimeAgo(item.createTime)}}
							</text>
						</view>
					</view>
				</view>
				<view class="message-row-foot">
					<u-icon name="error-circle" color="#f9ae3d" size="18" 
						v-if="item.status === 0" @click="updateMsgStatus(item,1)">
					</u-icon>
					<u-icon name="checkmark-circle-fill" color="#5ac725" size="18" 
						v-if="item.status === 1" @click="updateMsgStatus(item,0)">
					</u-icon>
					<u-icon name="close" size="18"
						@click="deleteMsg(item)">
					</u-icon>
				</view>
			</view>
			<u-loadmore v-if="msgList.length === 0" status="nomore" :line="true" />
		</scroll-view>
	</view>
</template>

<script>
	import api from '../../../request/api';
	import config from '../../../request/config';
	export default {
		data(){
			return {
				userInfo: {},
				READ_IMG_URL: config.READ_IMG_URL,
				list: [{
                    name: '待处理',
                }, {
                    name: '已完成',
                }],
				curNow: 0,
				triggered: false,
				msgList: [],
				formMsg: {
					currentPage: 1,
					pageSize: 10,
					msgStatus: 0,
					total: 0,
				},
				notData: false,
				isReset: false,
			}
		},
		onReady() {
			this.userInfo = uni.getStorageSync("loginUser");
			setTimeout(() => {
			    this.triggered = true;
			}, 500)
		},
		methods: {
			// 返回上个页面
			toBack() {
				uni.navigateBack({
					delta: 1, // 返回的页面数，1表示返回上一页
					animationType: 'pop-out', // 页面关闭的动画效果
					animationDuration: 300, // 页面关闭的动画时间
				});
			},
			//
			sectionChange(index){
				this.curNow = index;
				this.triggered = true;
			},
			// 获取消息列表
			getMsgList(){
				return new Promise(resolve =>{
					this.formMsg.msgStatus=this.curNow;
					api.getMsgNotificationList(this.formMsg).then(res =>{
						if (res.code === 200){
							if (this.isReset){
								this.msgList = [];
								this.isReset = false;
							}
							this.formMsg.total = res.data.total;
							resolve(res.data.total);
							if (res.data.msgVoList.length === 0){
								this.notData = true;
							}else {
								if (res.data.msgVoList.length < this.formMsg.pageSize){
									this.notData = true;
								}
								res.data.msgVoList.forEach(item =>{
									this.msgList.push(item);
								})
							}
						}
					})
				})
			},
			// 下拉刷新
			onRefresh() {
				console.log("====>自定义下拉刷新被触发<====")
				this.formMsg.currentPage = 1;
				this.formMsg.pageSize = 10;
				this.notData = false;
				this.isReset = true;
				this.getMsgList().then(res =>{
					this.triggered = false;
				});
			},
			// 下拉复位
			onRestore() {
				this.triggered = 'restore'; // 需要重置
			},
			// 滑动到底部
			onScroll(){
				if (this.notData){
					this.$tip.tip('没有更多消息了')
				}else {
					console.log("到底部");
					this.formMsg.currentPage++;
					this.getMsgList();
				}
			},
			// 页面跳转
			toPage(item){
				if (item.msgType === 1){
					// 公司文化
					if (item.submenu === 3){
						// 详情
						uni.navigateTo({
							url:"/pages/index/material?id="+item.relevanceId
						})
						this.updateMsgStatus(item,1);
					}
				}else if (item.msgType === 2){
					// 档案管理
					const path = "/goods/goods"
					uni.navigateTo({
						url:"/pages/workbench/webView?path="+path
					})
					this.updateMsgStatus(item,1);
				}else if (item.msgType === 3){
					// 员工考勤
					if (item.submenu === 5){
						// 考勤审批
						const path = "/employeeAttendance/apply"
						uni.navigateTo({
							url:"/pages/workbench/webView?path="+path
						})
						this.updateMsgStatus(item,1);
					}
				}else if (item.msgType === 4){
					// 客户管理
					const path = "/user/user"
					uni.navigateTo({
						url:"/pages/workbench/webView?path="+path
					})
					this.updateMsgStatus(item,1);
					
				}else if (item.msgType === 5){
					// 订单管理
					const path = "/order/orderList"
					uni.navigateTo({
						url:"/pages/workbench/webView?path="+path
					})
					this.updateMsgStatus(item,1);
				}else if (item.msgType === 6){
					// 仓库管理
					let path = ""
					if (item.submenu === 1){
						// 采购管理
						path = "/warehouse/purchase/purchasing"
					}else if (item.submenu === 2){
						// 入库管理
						path = "/warehouse/warehouse"
					}else if (item.submenu === 4){
						// 出库管理
						path = "/warehouse/outbound/outbound"
					}else if (item.submenu === 6){
						// 供应商管理
						path = "/warehouse/supplier/supplier"
					}else {
						// 采购详情
						path = "/warehouse/purchase/purchasing"
					}
					uni.navigateTo({
						url:"/pages/workbench/webView?path="+path
					})
					this.updateMsgStatus(item,1);
				}else if (item.msgType === 7){
					// 售后管理
					const path = "/afterSales/AfterDispatch"
					uni.navigateTo({
						url:"/pages/workbench/webView?path="+path
					})
					this.updateMsgStatus(item,1);
				}else if (item.msgType === 8){
					// 报销管理
					const path = "/expense/Expense"
					uni.navigateTo({
						url:"/pages/workbench/webView?path="+path
					})
					this.updateMsgStatus(item,1);
				}
			},
			// 修改消息状态
			updateMsgStatus(item,status){
				if (item.status !== status){
					const data = {
						msgId: item.id,
						msgStatus: status
					}
					api.updateMsgNotification(data).then(res =>{
						if (res.code === 200){
							// 将该消息从列表中删除
							const index = this.msgList.findIndex(msg =>msg.id===item.id);
							this.msgList.splice(index, 1);
						}
					})
				}
			},
			// 删除消息
			deleteMsg(item){
				const data = {
					msgId: item.id
				}
				api.deleteMsgNotification(data).then(res =>{
					if (res.code === 200){
						// 将该消息从列表中删除
						const index = this.msgList.findIndex(msg =>msg.id===item.id);
						this.msgList.splice(index, 1);
					}
				})
			},
			// 计算时间差
			formatTimeAgo(time){
				const now = new Date();
				const target = new Date(time);
				// 计算时间差（单位：毫秒）
				const diff = now.getTime() - target.getTime();
				// 小于1分钟，返回xx秒前
				if (diff < 60000) {
					const seconds = Math.floor(diff / 1000);
					return `${seconds}秒前`;
				}
				// 小于1小时，返回xx分钟前
				if (diff < 3600000) {
					const minutes = Math.floor(diff / 60000);
					return `${minutes}分钟前`;
				}
				// 小于1天，返回xx小时前
				if (diff < 86400000) {
					const hours = Math.floor(diff / 3600000);
					return `${hours}小时前`;
				}
				// 大于等于1天，返回年月日
				const year = target.getFullYear();
				const month = target.getMonth() + 1;
				const day = target.getDate();
				
				return `${year}-${month}-${day}`;
			}
		}
	}
</script>

<style>
	.message{
		width: 100%;
		min-height: 100vh;
		/* background-color: #eeeeef; */
	}
	
	.message-body{
		width: 94%;
		height: 85vh;
		margin: auto;
	}
	
	.message-row{
		width: 100%;
		padding: 10rpx 0;
		display: flex;
		/* border-top: 1px #e3e5e7 solid; */
	    border-bottom: 1px #e3e5e7 solid;
	}
	
	.message-row-foot{
		width: 40rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}
	
</style>